package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.adapter.HomePageListViewAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.BookListModel;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.BuySuccessEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.pay.UserBuyUtils;
import com.auto.learning.service.DownLoadManager;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.PuPSdPaySucceedDialog;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * 书单
 * @author wangjianjun
 */
public class BookListActivity extends Activity implements OnClickListener,Callback {
	private final static int GET_BOOK_LIST_INFO_SUCCESS = 1;
	private boolean ischeck = false;
	private PullToRefreshListView listview_list_book;
	private View headView;
	private LinearLayout activity_base_back,activity_base_more,linear_download;
	private TextView activity_base_titlename,tv_name,tv_intro,tv_intro_all,tv_launch,tv_download,tv_buy_booklist;
	private HomePageListViewAdapter adapter;
	private ArrayList<BookBean> list = new ArrayList<BookBean>();
	private BookListModel bookListModel;
	DisplayImageOptions options;
	private ImageView image_face,image_download;
	
	private Handle handler = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result =(ResponeResult) msg.obj;
				ArrayList<BookBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<BookBean>>() {}.getType());
				if (resultList != null) {
					list.clear();
					list.addAll(resultList);
					if (adapter != null) {
						adapter.notifyDataSetChanged();
					}
					if (listview_list_book != null) {
						listview_list_book.onRefreshComplete();
					}
					Cache.cacheChoosePageList2Local(list);
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(BookListActivity.this, msg.obj.toString());
				if (listview_list_book != null) {
					listview_list_book.onRefreshComplete();
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				CommonMethod.makeNotice(BookListActivity.this, "登录成功");
				ResponeResult login_result = (ResponeResult) msg.obj;
				if(login_result != null){
					EventBus.getEventBus("login_success_refreshUI").post(login_result);
					listview_list_book.clickRefresh();
					getBookListInfo();
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(BookListActivity.this, msg.obj.toString());
				break;
			case GET_BOOK_LIST_INFO_SUCCESS:
				ResponeResult book_result_info =(ResponeResult) msg.obj;
				bookListModel = new Gson().fromJson(book_result_info.getData(), new TypeToken<BookListModel>() {}.getType());
				if (bookListModel != null && !TextUtils.isEmpty(bookListModel.getName())) {
					showView();
				}
				break;
			case 5:
				DownLoadManager.getInstance(BookListActivity.this).addDownLoadId(msg.arg1);
				break;
			case 6:
				if (bookListModel != null && bookListModel.getListId() == msg.arg1) {
					PuPSdPaySucceedDialog dialog=new PuPSdPaySucceedDialog(BookListActivity.this);
					dialog.setImageUrl(bookListModel.getFaceImg());
					String str=String.format(getResources().getString(R.string.test_secceed_message),bookListModel.getName());
					dialog.setMessageText(str);
					dialog.show(activity_base_back);
					bookListModel.setNeedBuyCount(0);
					for (int i = 0; i < list.size(); i++) {
						list.get(i).setNeedBuy(1);
						if (adapter != null) {
							adapter.notifyDataSetChanged();
						}
					}
				}
				break;
			case 7:
				if (listview_list_book != null) {
					listview_list_book.clickRefresh();
				}
				break;
			}
		};
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.anchor_info_activity);
		initView();
		registerEvent();
		initImageLoader();
		TemporaryVariable.activities.push(this);
	}
	
	
	private void initView(){
		bookListModel = (BookListModel) getIntent().getSerializableExtra("data");
		listview_list_book = (PullToRefreshListView) findViewById(R.id.listview_anchor_book);
		adapter = new HomePageListViewAdapter(this, list);
		listview_list_book.setAdapter(adapter);
		
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		activity_base_more = (LinearLayout) findViewById(R.id.activity_base_more);
		activity_base_titlename = (TextView) findViewById(R.id.activity_base_titlename);
		activity_base_titlename.setText("推荐书单");
		activity_base_back.setOnClickListener(this);
		activity_base_more.setOnClickListener(this);
		
		headView = LayoutInflater.from(this).inflate(R.layout.book_list_activity_top, null);
		image_face = (ImageView) headView.findViewById(R.id.image_face);
		updateImageHight();
		tv_name = (TextView) headView.findViewById(R.id.tv_name);
		tv_intro = (TextView) headView.findViewById(R.id.tv_intro);
		tv_intro_all = (TextView) headView.findViewById(R.id.tv_intro_all);
		tv_download = (TextView) headView.findViewById(R.id.tv_download);
		tv_buy_booklist = (TextView) headView.findViewById(R.id.tv_buy_booklist);
		tv_buy_booklist.setOnClickListener(this);
		image_download = (ImageView) headView.findViewById(R.id.image_download);
		tv_intro.setTextIsSelectable(true);
		tv_intro_all.setTextIsSelectable(true);
		tv_launch = (TextView) headView.findViewById(R.id.tv_launch);
		linear_download = (LinearLayout) headView.findViewById(R.id.linear_download);
		if (bookListModel != null && !TextUtils.isEmpty(bookListModel.getName())) {
			showView();
		}
		tv_launch.setOnClickListener(this);
		linear_download.setOnClickListener(this);
		listview_list_book.addHeaderView(headView);
		listview_list_book.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				getBookList();
				getBookListInfo();
			}
		});
		listview_list_book.clickRefresh();
	}
	
	public void updateImageHight() {
		RelativeLayout.LayoutParams para = (android.widget.RelativeLayout.LayoutParams) image_face.getLayoutParams();
		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		para.height = width/ 5 * 2;
		image_face.setLayoutParams(para);
	}
	
	private void showView(){
		ImageLoader.getInstance().displayImage(bookListModel.getFaceImg(), image_face, options);
		tv_name.setText(bookListModel.getName()+"");
		tv_intro.setText(Html.fromHtml(bookListModel.getIntro()+""));
		tv_intro_all.setText(Html.fromHtml(bookListModel.getIntro()+""));
		tv_intro_all.setVisibility(View.GONE);
		int lineCont = getLineCount(Html.fromHtml(bookListModel.getIntro()+"").toString(), tv_intro_all);
		if (lineCont <= 3) {
			tv_launch.setVisibility(View.INVISIBLE);
		}else {
			tv_launch.setVisibility(View.VISIBLE);
		}
		if (bookListModel.getIsShare() == 2) {
			activity_base_more.setVisibility(View.VISIBLE);
		}else {
			activity_base_more.setVisibility(View.GONE);
		}
		tv_download.setTag("0");
		if (bookListModel.getNeedBuyCount() == bookListModel.getSumCount()) {
			tv_download.setTag("1");
			tv_download.setText("￥购买全书单书籍");
			image_download.setVisibility(View.INVISIBLE);
		}else {
			tv_download.setTag("2");
			tv_download.setText("下载");
			image_download.setVisibility(View.VISIBLE);
		}
		
		if (bookListModel.getNeedBuyCount() == 0 || bookListModel.getNeedBuyCount() == bookListModel.getSumCount()) {
			tv_buy_booklist.setVisibility(View.GONE);
		}else {
			tv_buy_booklist.setVisibility(View.VISIBLE);
		}
	}
	
	private int getLineCount(String str,TextView textView){
		float screenW = getWindowManager().getDefaultDisplay().getWidth();
		float paddingLeft = ((LinearLayout) textView.getParent()).getPaddingLeft();
		float paddingReft = ((LinearLayout) textView.getParent()).getPaddingRight();
		// 这里具体this.getPaint()要注意使用，要看你的TextView在什么位置，这个是拿TextView父控件的Padding的，为了更准确的算出换行
		int line = (int) Math.ceil((textView.getPaint().measureText(str) / (screenW - paddingLeft - paddingReft)));
		return line;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_base_back:
			finish();
			break;
		case R.id.activity_base_more:
			if (bookListModel != null) {
				String url = bookListModel.getShareUrl()+"";
				String content = bookListModel.getShareSmallTitle()+"";
				String title = bookListModel.getShareTitle()+"";
				new ShareView(this, this).setTitle(title).setUrl(url).setContent(content).setImageUrl(bookListModel.getFaceImg()).setType(8).setId(bookListModel.getListId()+"").show(findViewById(R.id.main_view));
			}
			break;
		case R.id.tv_launch:
			if (tv_intro.getVisibility() == View.VISIBLE) {
				tv_intro.setVisibility(View.GONE);
				tv_intro_all.setVisibility(View.VISIBLE);
				tv_launch.setText("收起");
			}else {
				tv_intro.setVisibility(View.VISIBLE);
				tv_intro_all.setVisibility(View.GONE);
				tv_launch.setText("展开");
			}
			break;
		case R.id.linear_download:
			
			linear_download.setEnabled(false);
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					linear_download.setEnabled(true);
				}
			}, 2000);
			if (tv_download.getTag().toString().equals("2")) {
				if (new UserBuyUtils(BookListActivity.this, bookListModel, 4).buy()) {
					downloadAll();	
				}
			}else if (tv_download.getTag().toString().equals("1")){
				if (new UserBuyUtils(BookListActivity.this, bookListModel, 5).buy()) {
					downloadAll();	
				}
			}
			break;
		case R.id.tv_buy_booklist:
			new UserBuyUtils(BookListActivity.this, bookListModel, 5).buy();
			break;
		}
	}
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.banner)
		.showImageForEmptyUri(R.drawable.banner)
		.showImageOnFail(R.drawable.banner).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
	
	private void getBookList(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("listId", String.valueOf(bookListModel.getListId())));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.BOOK_LIST_DETAIL, params, handler, HttpRequestHelper.GETDATA_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}
	
	private void getBookListInfo(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("listId", String.valueOf(bookListModel.getListId())));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.BOOK_LIST_INFO, params, handler, GET_BOOK_LIST_INFO_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		MusicPlayManager.getInstance(this).setPlaying(isPlaying);
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}
	
	@Subscribe
	public void onEventBuyBookListSuccess(Integer listId){
		handler.obtainMessage(6, listId, 0).sendToTarget();
	}
	
	@Subscribe
	public void onEventBuyBookSuccess(BuySuccessEvent buySuccessEvent){
		handler.sendEmptyMessage(7);
	}
	
	public void registerEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_buy_book_list_success" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_buy_success" , ThreadEnforcer.MAIN).register(this);
	}
	
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_buy_book_list_success" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_buy_success" , ThreadEnforcer.MAIN).unregister(this);
	}


	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(this, msg);
		return false;
	}
	
	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		unRegisterEvent();
		super.onDestroy();
	}
	
	/**
	 * 下载所以免费作品
	 */
	public void downloadByFree() {
		if (list != null && list.size() > 0 && CommonMethod.checkUserLogin(BookListActivity.this)) {
			if(ischeck == false){
				ArrayList<Integer> bookIds = new ArrayList<Integer>();
				int allSize = 0;
				for (BookBean item : list) {
					if (!TemporaryVariable.downLoadedList.contains(item.getBookId()) && item.getNeedBuy() == 1) {
						bookIds.add(item.getBookId());
						allSize += (item.getProSize() + item.getDoubiSize() + item.getEnSize());
					}
				}
				if (bookIds.size() > 0) {
					ischeck = true;
					prepareBefore(allSize, bookIds);
				}
			}else{
				CommonMethod.makeNotice(BookListActivity.this, "已经加入下载列表");
			}
		}
	}
	
	
	/**
	 * 下载所有推荐作品
	 */
	public void downloadAll(){
		if (list != null && list.size() > 0 && CommonMethod.checkUserLogin(BookListActivity.this)) {
			if(ischeck == false){
				ArrayList<Integer> bookIds = new ArrayList<Integer>();
				int allSize = 0;
				for (BookBean item : list) {
					if (!TemporaryVariable.downLoadedList.contains(item.getBookId())) {
						bookIds.add(item.getBookId());
						allSize += (item.getProSize() + item.getDoubiSize() + item.getEnSize());
					}
				}
				if (bookIds.size() > 0) { 
					ischeck=true;
					prepareBefore(allSize, bookIds);
				}
			}else{
				CommonMethod.makeNotice(BookListActivity.this, "已经加入下载列表");
			}
		}
	}
	
	/**
	 * 批量下载
	 * @param allSize
	 * @param bookIds
	 */
	public void prepareBefore(int allSize , final ArrayList<Integer> bookIds){
		if (!(boolean)SharedPreferencesUtils.getParam(BookListActivity.this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
			switch (CommonMethod.getNetworkState(BookListActivity.this)) {
			case 0:
				CommonMethod.makeNotice(BookListActivity.this, getResources().getString(R.string.connect_err_io));
				break;
			case 1:
				/*for (int i = 0; i < bookIds.size(); i++) {
//					DownLoadManager.getInstance(getActivity()).setNeedDownLoadBookId(bookIds.get(i)).prepare();
					DownLoadManager.getInstance(BookListActivity.this).setContext(BookListActivity.this).addDownLoadId(bookIds.get(i));
				}*/
				add2DownLoadList(bookIds);
//				DownLoadManager.getInstance(BookListActivity.this).setContext(BookListActivity.this).addDownLoadIds(bookIds);
				break;
			case 2:
				CommonAlertDialog alertDialog = new CommonAlertDialog(BookListActivity.this);
				alertDialog.setTextMessage(String.format(getResources().getString(R.string.download_notice), CommonMethod.calculationNum(allSize)));
				alertDialog.setShowTitle(true);
				String[] a = {getResources().getString(R.string.app_continue),getResources().getString(R.string.app_cancel)};
				alertDialog.setBtns(new DialogListener() {
					
					@Override
					public void otherButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
					
					@Override
					public void okButtonClick(Dialog dialog) {
						/*for (int i = 0; i < bookIds.size(); i++) {
							DownLoadManager.getInstance(BookListActivity.this).setContext(BookListActivity.this).addDownLoadId(bookIds.get(i));
						}*/
						add2DownLoadList(bookIds);
//						DownLoadManager.getInstance(BookListActivity.this).setContext(BookListActivity.this).addDownLoadIds(bookIds);
						dialog.dismiss();
					}
					
					@Override
					public void cancelButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
				},a);
				alertDialog.show();
				break;
			  }
			} else {
				/*for (int i = 0; i < bookIds.size(); i++) {
					DownLoadManager.getInstance(BookListActivity.this).addDownLoadId(bookIds.get(i));
				}*/
				add2DownLoadList(bookIds);
//				DownLoadManager.getInstance(BookListActivity.this).addDownLoadIds(bookIds);
			}
	}
	
	private void add2DownLoadList(final ArrayList<Integer> bookIds){
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < bookIds.size(); i++) {
					handler.obtainMessage(5, bookIds.get(i), 0).sendToTarget();
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(BookListActivity.this,data.getStringExtra("userId"), data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handler);
				}
			});
		}else if (requestCode == 100 && resultCode == 204) {
			if (listview_list_book != null) {
				listview_list_book.clickRefresh();
				getBookListInfo();
			}
			EventBus.getEventBus("login_refreshUI").post(new LoginSuccessEvent());
		}
	}
	
}
